<template>
  <div class="settings-page">
    <h2>云同步设置</h2>
    
    <div class="settings-section">
      <n-form
        ref="formRef"
        :model="cloudSettings"
        label-placement="left"
        label-width="160"
        require-mark-placement="right-hanging"
      >
        <!-- 同步状态 -->
        <n-divider>同步状态</n-divider>
        
        <div class="sync-status">
          <n-space vertical :size="12">
            <n-alert :type="syncStatusType" style="max-width: 600px">
              <template #icon>
                <n-icon>
                  <component :is="syncStatusIcon" />
                </n-icon>
              </template>
              <template #header>
                {{ syncStatusText }}
              </template>
              <div>{{ syncStatusDescription }}</div>
              <template #footer v-if="syncError">
                <n-button text type="error" @click="showErrorDetails">
                  查看详情
                </n-button>
              </template>
            </n-alert>
            
            <n-space>
              <n-button 
                type="primary" 
                :loading="syncLoading" 
                :disabled="!isLoggedIn" 
                @click="syncNow"
              >
                <template #icon><n-icon><CloudSyncOutline /></n-icon></template>
                立即同步
              </n-button>
              <n-button quaternary @click="refreshStatus" :disabled="syncLoading">
                <template #icon><n-icon><RefreshOutline /></n-icon></template>
                刷新状态
              </n-button>
            </n-space>
          </n-space>
        </div>
        
        <!-- 同步选项 -->
        <n-divider>同步选项</n-divider>
        
        <n-form-item label="启用云同步" path="enableSync">
          <n-switch v-model:value="cloudSettings.enableSync" />
        </n-form-item>
        
        <n-form-item label="自动同步" path="autoSync" v-if="cloudSettings.enableSync">
          <n-switch v-model:value="cloudSettings.autoSync" />
        </n-form-item>
        
        <n-form-item label="同步频率" path="syncInterval" v-if="cloudSettings.enableSync && cloudSettings.autoSync">
          <n-select
            v-model:value="cloudSettings.syncInterval"
            :options="syncIntervalOptions"
            style="width: 200px"
          />
        </n-form-item>
        
        <n-form-item label="同步内容" path="syncContent" v-if="cloudSettings.enableSync">
          <n-space vertical align="start">
            <n-checkbox v-model:checked="cloudSettings.syncProjects">项目文件</n-checkbox>
            <n-checkbox v-model:checked="cloudSettings.syncAssets">素材资源</n-checkbox>
            <n-checkbox v-model:checked="cloudSettings.syncSettings">应用设置</n-checkbox>
          </n-space>
        </n-form-item>
        
        <n-form-item label="冲突解决策略" path="conflictStrategy" v-if="cloudSettings.enableSync">
          <n-radio-group v-model:value="cloudSettings.conflictStrategy">
            <n-space vertical>
              <n-radio value="askEveryTime">每次询问</n-radio>
              <n-radio value="localOverCloud">本地覆盖云端</n-radio>
              <n-radio value="cloudOverLocal">云端覆盖本地</n-radio>
              <n-radio value="keepBoth">保留两者</n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>
        
        <!-- 存储空间 -->
        <n-divider>存储空间</n-divider>
        
        <div class="storage-info">
          <n-space vertical :size="12">
            <n-progress
              type="line"
              :percentage="storagePercentage"
              :color="storageColorMap"
              :height="18"
              :border-radius="5"
              :show-indicator="false"
              :processing="syncLoading"
            >
              <div class="progress-info">
                已使用 {{ formatStorage(usedStorage) }} / {{ formatStorage(totalStorage) }}
              </div>
            </n-progress>
            
            <n-space align="center" justify="space-between" style="width: 100%;">
              <div class="storage-detail">
                <n-space>
                  <div class="storage-item">
                    <div class="storage-label">项目</div>
                    <div class="storage-value">{{ formatStorage(projectStorage) }}</div>
                  </div>
                  <div class="storage-item">
                    <div class="storage-label">素材</div>
                    <div class="storage-value">{{ formatStorage(assetStorage) }}</div>
                  </div>
                  <div class="storage-item">
                    <div class="storage-label">其他</div>
                    <div class="storage-value">{{ formatStorage(otherStorage) }}</div>
                  </div>
                </n-space>
              </div>
              <n-button @click="upgradeStorage" :disabled="!isLoggedIn">
                <template #icon><n-icon><ArrowUpCircleOutline /></n-icon></template>
                升级存储空间
              </n-button>
            </n-space>
          </n-space>
        </div>
        
        <!-- 离线模式 -->
        <n-divider>离线模式</n-divider>
        
        <n-form-item label="启用离线工作模式" path="offlineMode">
          <n-switch v-model:value="cloudSettings.offlineMode" />
        </n-form-item>
        
        <n-form-item label="离线缓存" path="offlineCache" v-if="!cloudSettings.offlineMode">
          <n-space vertical align="start">
            <n-checkbox v-model:checked="cloudSettings.cacheProjects">缓存项目文件</n-checkbox>
            <n-checkbox v-model:checked="cloudSettings.cacheAssets">缓存素材资源</n-checkbox>
          </n-space>
        </n-form-item>
        
        <n-form-item label="缓存大小限制" path="maxCacheSize" v-if="!cloudSettings.offlineMode && (cloudSettings.cacheProjects || cloudSettings.cacheAssets)">
          <n-input-number
            v-model:value="cloudSettings.maxCacheSize"
            :min="100"
            :max="10000"
            style="width: 150px"
          >
            <template #suffix>MB</template>
          </n-input-number>
        </n-form-item>
        
        <n-form-item label="清理缓存" v-if="!cloudSettings.offlineMode && (cloudSettings.cacheProjects || cloudSettings.cacheAssets)">
          <n-space>
            <n-button @click="clearCache('projects')" :disabled="syncLoading">
              清理项目缓存
            </n-button>
            <n-button @click="clearCache('assets')" :disabled="syncLoading">
              清理素材缓存
            </n-button>
            <n-button @click="clearCache('all')" :disabled="syncLoading">
              清理所有缓存
            </n-button>
          </n-space>
        </n-form-item>
      </n-form>
      
      <div class="form-actions">
        <n-space>
          <n-button @click="resetToDefaults" quaternary>恢复默认设置</n-button>
          <n-button type="primary" @click="saveSettings">保存设置</n-button>
        </n-space>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useMessage } from 'naive-ui'
import {
  NForm,
  NFormItem,
  NSwitch,
  NSelect,
  NCheckbox,
  NRadioGroup,
  NRadio,
  NButton,
  NSpace,
  NDivider,
  NProgress,
  NAlert,
  NIcon,
  NInputNumber
} from 'naive-ui'
import {
  CloudSyncOutline,
  RefreshOutline,
  ArrowUpCircleOutline,
  CheckmarkCircleOutline,
  CloseCircleOutline,
  AlertCircleOutline,
  HourglassOutline
} from '@vicons/ionicons5'

const message = useMessage()
const formRef = ref(null)

// 云同步设置表单
const cloudSettings = reactive({
  enableSync: true,
  autoSync: true,
  syncInterval: 'hourly',
  syncProjects: true,
  syncAssets: true,
  syncSettings: true,
  conflictStrategy: 'askEveryTime',
  offlineMode: false,
  cacheProjects: true,
  cacheAssets: true,
  maxCacheSize: 1000
})

// 同步频率选项
const syncIntervalOptions = [
  { label: '每小时', value: 'hourly' },
  { label: '每天', value: 'daily' },
  { label: '每周', value: 'weekly' },
  { label: '手动', value: 'manual' }
]

// 同步状态
const syncStatus = ref('unknown') // 'synced', 'syncing', 'error', 'offline', 'unknown'
const syncLoading = ref(false)
const syncError = ref(null)
const lastSyncTime = ref(null)
const isLoggedIn = ref(true) // 实际项目中应从用户状态获取

// 存储空间信息
const usedStorage = ref(1024 * 2.5) // MB
const totalStorage = ref(1024 * 10) // MB
const projectStorage = ref(1024 * 1.8) // MB
const assetStorage = ref(1024 * 0.5) // MB
const otherStorage = ref(1024 * 0.2) // MB

// 计算存储百分比
const storagePercentage = computed(() => {
  return Math.min(100, Math.round((usedStorage.value / totalStorage.value) * 100))
})

// 存储颜色映射
const storageColorMap = computed(() => {
  const percentage = storagePercentage.value
  if (percentage < 70) return '#18a058'
  if (percentage < 90) return '#f0a020'
  return '#d03050'
})

// 同步状态文本
const syncStatusText = computed(() => {
  switch (syncStatus.value) {
    case 'synced':
      return '已同步'
    case 'syncing':
      return '正在同步...'
    case 'error':
      return '同步出错'
    case 'offline':
      return '离线模式'
    default:
      return '未知状态'
  }
})

// 同步状态描述
const syncStatusDescription = computed(() => {
  switch (syncStatus.value) {
    case 'synced':
      return `所有内容已同步至云端。上次同步时间: ${formatTime(lastSyncTime.value)}`
    case 'syncing':
      return '正在将本地更改同步至云端，请稍候...'
    case 'error':
      return '同步过程中发生错误，请检查网络连接或重试。'
    case 'offline':
      return '当前处于离线模式，更改将不会同步至云端。'
    default:
      return '无法获取同步状态，请检查网络连接。'
  }
})

// 同步状态图标
const syncStatusIcon = computed(() => {
  switch (syncStatus.value) {
    case 'synced':
      return CheckmarkCircleOutline
    case 'syncing':
      return HourglassOutline
    case 'error':
      return CloseCircleOutline
    case 'offline':
      return AlertCircleOutline
    default:
      return AlertCircleOutline
  }
})

// 同步状态类型
const syncStatusType = computed(() => {
  switch (syncStatus.value) {
    case 'synced':
      return 'success'
    case 'syncing':
      return 'info'
    case 'error':
      return 'error'
    case 'offline':
      return 'warning'
    default:
      return 'warning'
  }
})

// 格式化存储大小
function formatStorage(size: number): string {
  if (size < 1024) {
    return `${size.toFixed(2)} MB`
  } else {
    return `${(size / 1024).toFixed(2)} GB`
  }
}

// 格式化时间
function formatTime(time: Date | null): string {
  if (!time) return '未知'
  return time.toLocaleString()
}

// 立即同步
function syncNow() {
  if (!isLoggedIn.value) {
    message.warning('请先登录账号')
    return
  }
  
  syncLoading.value = true
  syncStatus.value = 'syncing'
  
  // 模拟同步过程
  setTimeout(() => {
    const success = Math.random() > 0.2 // 80%概率成功
    
    if (success) {
      syncStatus.value = 'synced'
      lastSyncTime.value = new Date()
      message.success('同步成功')
    } else {
      syncStatus.value = 'error'
      syncError.value = {
        code: 'NETWORK_ERROR',
        message: '网络连接超时，请稍后重试'
      }
      message.error('同步失败')
    }
    
    syncLoading.value = false
  }, 2000)
}

// 刷新状态
function refreshStatus() {
  syncLoading.value = true
  
  // 模拟刷新过程
  setTimeout(() => {
    if (cloudSettings.offlineMode) {
      syncStatus.value = 'offline'
    } else if (Math.random() > 0.2) {
      syncStatus.value = 'synced'
      lastSyncTime.value = new Date(Date.now() - Math.random() * 86400000)
    } else {
      syncStatus.value = 'error'
      syncError.value = {
        code: 'AUTH_ERROR',
        message: '授权已过期，请重新登录'
      }
    }
    
    syncLoading.value = false
  }, 1000)
}

// 显示错误详情
function showErrorDetails() {
  if (!syncError.value) return
  
  message.error(`错误代码: ${syncError.value.code}, 错误信息: ${syncError.value.message}`)
}

// 升级存储空间
function upgradeStorage() {
  message.info('即将跳转到存储空间升级页面')
  // 实际项目中，这里会跳转到升级页面或打开对话框
}

// 清理缓存
function clearCache(type: 'projects' | 'assets' | 'all') {
  const typeText = {
    projects: '项目',
    assets: '素材',
    all: '所有'
  }[type]
  
  message.info(`正在清理${typeText}缓存...`)
  
  // 模拟清理过程
  setTimeout(() => {
    message.success(`${typeText}缓存已清理`)
    
    // 更新缓存大小
    if (type === 'projects' || type === 'all') {
      projectStorage.value = 0
    }
    
    if (type === 'assets' || type === 'all') {
      assetStorage.value = 0
    }
    
    if (type === 'all') {
      otherStorage.value = 0
    }
    
    usedStorage.value = projectStorage.value + assetStorage.value + otherStorage.value
  }, 1500)
}

// 默认设置
const defaultSettings = {
  enableSync: true,
  autoSync: true,
  syncInterval: 'hourly',
  syncProjects: true,
  syncAssets: true,
  syncSettings: true,
  conflictStrategy: 'askEveryTime',
  offlineMode: false,
  cacheProjects: true,
  cacheAssets: true,
  maxCacheSize: 1000
}

// 加载设置
function loadSettings() {
  // 实际项目中，这里会从本地存储或API加载设置
  const savedSettings = localStorage.getItem('cloudSettings')
  if (savedSettings) {
    try {
      const parsedSettings = JSON.parse(savedSettings)
      Object.assign(cloudSettings, parsedSettings)
    } catch (error) {
      console.error('Failed to parse saved settings:', error)
    }
  }
}

// 保存设置
function saveSettings() {
  // 实际项目中，这里会调用API保存设置
  localStorage.setItem('cloudSettings', JSON.stringify(cloudSettings))
  message.success('设置已保存')
  
  // 应用设置
  applySettings()
}

// 应用设置
function applySettings() {
  // 如果开启离线模式
  if (cloudSettings.offlineMode) {
    syncStatus.value = 'offline'
  }
  
  // 实际项目中，这里会应用更多设置
  console.log('Cloud settings applied:', cloudSettings)
}

// 恢复默认设置
function resetToDefaults() {
  Object.assign(cloudSettings, defaultSettings)
  message.info('已恢复默认设置')
}

// 组件挂载时加载设置
onMounted(() => {
  loadSettings()
  refreshStatus()
})
</script>

<style lang="scss" scoped>
.settings-page {
  padding: 0 16px;
  
  h2 {
    margin-top: 0;
    margin-bottom: 24px;
    font-weight: 500;
  }
  
  .settings-section {
    max-width: 800px;
  }
  
  .sync-status {
    margin-bottom: 20px;
  }
  
  .storage-info {
    margin-bottom: 20px;
    
    .progress-info {
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 12px;
      text-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
    }
    
    .storage-detail {
      margin-top: 8px;
      
      .storage-item {
        padding: 0 16px;
        border-right: 1px solid var(--border-color);
        
        &:last-child {
          border-right: none;
        }
        
        .storage-label {
          font-size: 12px;
          color: var(--text-color-3);
        }
        
        .storage-value {
          font-size: 14px;
          font-weight: 500;
        }
      }
    }
  }
  
  .form-actions {
    margin-top: 32px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 